#删除mysql及其相关依赖包
echo "正在删除mysql及其相关依赖包..."
rpm -qa | grep -i mysql | xargs rpm -e --nodeps
echo "Done."

#删除mysql所涉及的安装目录
echo "正在删除mysql所涉及的安装目录..."
whereis mysql | xargs rm -rf
echo "Done."

#删除所有和mysql相关的目录
echo "正在删除所有和mysql相关的目录..."
find / -name mysql | xargs rm -rf
echo "Done."

#删除所有配置文件
echo "正在删除所有配置文件..."
find / -name my.cnf* | xargs rm -rf
echo "Done."

echo "正在删除mysql开机自启动服务..."
#删除mysql开机自启动服务
chkconfig --del mysqld
echo "Done."

#解决yum被锁的情况
echo "正在防止yum被锁..."
rm -f /var/run/yum.pid
echo "Done."

##   为了解决'安装mysql安装源'步骤时发生如下错误：
#    Warning: RPMDB altered outside of yum.
#    Found 2 pre-existing rpmdb problem(s), 'yum check' output follows:
#    2:postfix-2.10.1-6.el7.x86_64 has missing requires of libmysqlclient.so.18()(64bit)
#    2:postfix-2.10.1-6.el7.x86_64 has missing requires of libmysqlclient.so.18(libmysqlclient_18)(64bit)

echo "正在安装Deltarpm包（增量 RPM 套件）..."
yum provides '*/applydeltarpm'  #安装Deltarpm包（增量 RPM 套件）
yum install deltarpm -y
echo "Done."

echo "正在配置正确的yum源..."
echo "Done."

yum install epel-release -y #配置正确的yum源
echo "正在清除本地yum缓存..."
yum clean all  ##清除本地yum缓存
echo "Done."

echo "正在同步本地软件和epel源的软件包信息..."
yum distro-sync ##同步本地软件和epel源的软件包信息
echo "Done."

#下载MySQL安装
echo "正在下载MySQL安装包..."
wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
echo "Done."

#安装mysql安装源
echo "正在安装mysql安装源..."
yum -y localinstall mysql57-community-release-el7-11.noarch.rpm
echo "Done."

#在线安装MySQL
echo "正在安装MySQL...."
yum -y install mysql-community-server
echo "Done."

#启动MySQL服务
echo "正在启动MySQL服务..."
systemctl start mysqld
echo "Done."

#设置开机启动
echo "正在配置开机自启..."
systemctl enable mysqld
systemctl daemon-reload
echo "Done."

#防火墙开放3306端口
echo "正在开放3306端口..."
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --reload
echo "Done."

#配置mysql默认编码为utf-8
echo "配置mysql默认编码为utf-8..."
echo "character_set_server=utf8" >> /etc/my.cnf
echo "init_connect='SET NAMES utf8'" >> /etc/my.cnf
echo "Done."

#从mysqld.log文件中找到临时生成的密码所在行
PWD=`cat /var/log/mysqld.log | grep root@localhost`
#截取获取密码
PWD=${PWD##*:}
echo "------------------------------- Note ------------------------------------"
echo "mysql5.7默认密码策略要求密码必须是大小写字母数字特殊字母的组合，至少8位"
echo "你的临时密码:"$PWD"             your temporary password:"$PWD
echo "-------------------------------------------------------------------------"
echo ""
echo "接下来你只需要一步步复制执行即可"
echo "step1.  mysql -u root -p"
echo "step2.  ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOUR_PASSWORD';"
echo "step3.  GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'YOUR_PASSWORD' WITH GRANT OPTION;"
echo "step4.  FLUSH PRIVILEGES;"
echo "step5.  EXIT"
echo "step6.  systemctl restart mysqld"

